package com.koron.plan.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.CacheKeyPrefix;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializationContext;

import java.time.Duration;

/**
 * @author twcao
 * @title: CacheConfig
 * @projectName GDH_EAM_V2
 * @description: redis缓存
 * @date 2021/11/1616:50
 */
@Configuration
public class CacheConfig extends CachingConfigurerSupport {

    private static final String SYSTEM_CACHE_REDIS_KEY_PREFIX = "eam:plan";

    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    @Autowired
    private RedisTemplate redisTemplate;

    @Bean
    @Override
    public CacheManager cacheManager() {
        // 默认30分钟过期
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisTemplate.getValueSerializer()))
                .computePrefixWith(cacheKeyPrefix()).entryTtl(Duration.ofMinutes(30));
        return RedisCacheManager.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory)).cacheDefaults(redisCacheConfiguration).build();
    }

    @Bean
    public CacheKeyPrefix cacheKeyPrefix() {
        return cacheName -> {
            StringBuilder sb = new StringBuilder(100);
            sb.append(SYSTEM_CACHE_REDIS_KEY_PREFIX).append(":");
            sb.append(cacheName).append(":");
            return sb.toString();
        };
    }
}
